﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Brain.IO
{
    public class TerrainFile
    {
        public float[,] Heights;
        public float DistanceBetweenHeights;

        public TerrainFile()
        {
        }

        public void Serialize(Stream stream)
        {
            using (BinaryWriter writer = new BinaryWriter(stream))
            {
                writer.Write("BRAINTERRAIN");
                int width = Heights.GetLength(0);
                int height = Heights.GetLength(1);

                writer.Write(width);
                writer.Write(height);
                writer.Write(this.DistanceBetweenHeights);

                for (int x = 0; x < width; x++)
                {
                    for (int z = 0; z < height; z++)
                    {
                        writer.Write(Heights[x, z]);
                    }
                }
            }
        }

        public void Deserialize(Stream stream)
        {
            using (BinaryReader reader = new BinaryReader(stream))
            {
                string s = reader.ReadString();
                if (s != "BRAINTERRAIN")
                {
                    throw new Exception("Header doesn't look like a Brain Terrain file!");
                }

                int width = reader.ReadInt32();
                int height = reader.ReadInt32();
                this.DistanceBetweenHeights = reader.ReadSingle();
                this.Heights = new float[width, height];

                for (int x = 0; x < width; x++)
                {
                    for (int z = 0; z < height; z++)
                    {
                        this.Heights[x, z] = reader.ReadSingle();
                    }
                }
            }
        }

        public HeightMap MakeHeightMap()
        {
            HeightMap map = new HeightMap();
            map.Width = this.Heights.GetLength(0);
            map.Height = this.Heights.GetLength(1);
            map.Heights = this.Heights;
            map.OffsetBetweenHeights = this.DistanceBetweenHeights;
            return map;
        }
    }
}
